import 'package:bilibili/http/dao/like_dao.dart';
import 'package:bilibili/http/model/video_model.dart';
import 'package:hi_common/util/color.dart';
import 'package:hi_common/util/format_utils.dart';
import 'package:hi_common/util/logger.dart';
import 'package:bilibili/widget/video_detail_card.dart';
import 'package:bilibili/widget/video_toolbar.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hi_net/http/core/hi_error.dart';

import '../http/dao/favorite_dao.dart';
import '../http/model/owner.dart';
import '../http/model/video_detail_mo.dart';
import '../util/toast.dart';
import '../widget/common_widget.dart';

class IntroductionPage extends StatefulWidget {
  final VideoDetailMo? model;
  final VideoModel videoInfo;

  const IntroductionPage({super.key, required this.videoInfo, this.model});

  @override
  State<StatefulWidget> createState() {
    return _IntroductionPageState();
  }
}

class _IntroductionPageState extends State<IntroductionPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  bool _expand = false;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(duration: const Duration(seconds: 2), vsync: this)
          ..drive(CurveTween(curve: Curves.ease));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        _ownerCard(),
        _buildUserInfo(),
        _buildStatistic(),
        _buildDesc(widget.videoInfo.desc),
        const Padding(padding: EdgeInsets.only(top: 10)),
        _buildVideoToolBar(),
        const Divider(thickness: 0.2, color: Colors.grey),
        ..._buildVideoList()
      ],
    );
  }

  _buildVideoToolBar() {
    if (widget.model != null) {
      return Padding(
          padding: const EdgeInsets.only(left: 15, right: 15),
          child: VideoToolBar(
            model: widget.model!,
            onLike: () {
              _doLike(widget.model!.videoInfo.vid, () {
                setState(() {
                  widget.model!.isLike = true;
                  widget.model!.videoInfo.like += 1;
                });
              });
            },
            unLike: () {
              _unLike(widget.model!.videoInfo.vid, () {
                setState(() {
                  widget.model!.isLike = false;
                  widget.model!.videoInfo.like -= 1;
                });
              });
            },
            onFavorite: () {
              _doFavorite(widget.model!.videoInfo.vid, () {
                setState(() {
                  widget.model!.isFavorite = true;
                  widget.model!.videoInfo.favorite += 1;
                });
              });
            },
            unFavorite: () {
              _unFavorite(widget.model!.videoInfo.vid, () {
                setState(() {
                  widget.model!.isFavorite = false;
                  widget.model!.videoInfo.favorite -= 1;
                });
              });
            },
          ));
    }
    return Container();
  }

  _buildVideoList() {
    var list = List.empty(growable: true);
    if (widget.model != null) {
      var videoList = widget.model!.videoList;
      var length = videoList.length;
      for (int i = 0; i < length; i++) {
        var model = videoList[i];
        var videoDetailCard = Padding(
            padding: const EdgeInsets.only(left: 15, right: 15),
            child: VideoDetailCard(model));
        list.add(videoDetailCard);
        if (i != length - 1) {
          var divider = const Divider(
            thickness: 0.2,
            color: Colors.grey,
          );
          list.add(divider);
        }
      }
    }
    return list;
  }

  _buildUserInfo() {
    return Padding(
        padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
                child: Text(
              widget.videoInfo.title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            )),
            const SizedBox(
              width: 15,
            ),
            InkWell(
              onTap: () {
                _toggleDesc();
              },
              child: _expand
                  ? const Icon(Icons.keyboard_arrow_down)
                  : const Icon(Icons.keyboard_arrow_up),
            )
          ],
        ));
  }

  _toggleDesc() {
    setState(() {
      _expand = !_expand;
      if (_expand) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  _buildDesc(String desc) {
    var widget = _expand
        ? Text(
            desc,
            style: const TextStyle(fontSize: 11, color: Colors.grey),
          )
        : null;

    return Padding(
      padding: const EdgeInsets.only(left: 15, right: 15),
      child: AnimatedBuilder(
          animation: _animationController.view,
          builder: (BuildContext context, Widget? child) {
            return Align(
              alignment: Alignment.topCenter,
              heightFactor: _animationController.value,
              child: Container(
                alignment: Alignment.topLeft,
                child: child,
              ),
            );
          },
          child: widget),
    );
  }

  Widget _ownerCard() {
    return Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _owner(widget.videoInfo.owner),
            InkWell(
              onTap: () {
                //todo
                logger.i("关注");
              },
              child: const Material(
                  color: primary,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(2))),
                  child: Padding(
                    padding:
                        EdgeInsets.only(left: 15, right: 15, top: 2, bottom: 2),
                    child: Text(
                      "+ 关注",
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  )),
            )
          ],
        ));
  }

  Widget _owner(Owner owner) {
    return Row(children: [
      ClipOval(
        child: Image.network(owner.face, width: 30, height: 30),
      ),
      Padding(
          padding: const EdgeInsets.only(left: 5),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                owner.name,
                style: const TextStyle(fontSize: 14, color: primary),
              ),
              Text(
                "${countFormat(owner.fans)}粉丝",
                style: TextStyle(fontSize: 11, color: Colors.grey[600]),
              )
            ],
          ))
    ]);
  }

  _buildStatistic() {
    var dateStr = widget.videoInfo.createTime.length > 10
        ? widget.videoInfo.createTime.substring(5, 10)
        : widget.videoInfo.createTime;
    return Padding(
        padding: const EdgeInsets.only(top: 5, left: 15, right: 15),
        child: Row(
          children: [
            ...smallIconText(
                Icons.ondemand_video, countFormat(widget.videoInfo.view)),
            const Padding(padding: EdgeInsets.only(left: 5)),
            ...smallIconText(
                Icons.list_alt, countFormat(widget.videoInfo.reply)),
            const Padding(padding: EdgeInsets.only(left: 5)),
            ...smallIconText(null, dateStr)
          ],
        ));
  }

  _doLike(String vid, VoidCallback? onSuccess) async {
    try {
      var response = await LikeDao.like(vid, true);
      onSuccess?.call();
      showToast(response['msg'], gravity: ToastGravity.BOTTOM);
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    } catch (e) {
      logger.e(e);
    }
  }

  _unLike(String vid, VoidCallback? onSuccess) async {
    try {
      var response = await LikeDao.like(vid, false);
      onSuccess?.call();
      showToast(response['msg'], gravity: ToastGravity.BOTTOM);
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    } catch (e) {
      logger.e(e);
    }
  }

  _doFavorite(String vid, VoidCallback? onSuccess) async {
    try {
      var response = await FavoriteDao.favorite(vid, true);
      onSuccess?.call();
      showToast(response['msg'], gravity: ToastGravity.BOTTOM);
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    } catch (e) {
      logger.e(e);
    }
  }

  _unFavorite(String vid, VoidCallback? onSuccess) async {
    try {
      var response = await FavoriteDao.favorite(vid, false);
      onSuccess?.call();
      showToast(response['msg'], gravity: ToastGravity.BOTTOM);
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    } catch (e) {
      logger.e(e);
    }
  }
}
